﻿using Cinch;
using FR.SAFTAnalyserLite.ViewModels.Workspace;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FR.SAFTAnalyserLite.SAFT
{
    public static class XmlSerializer
    {
        public static T Deserialize<T>(string xmlString)
        {
            TextReader tw = null;
            try
            {
                tw = new StreamReader(xmlString);

                System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(T));
                T config = (T)x.Deserialize(tw);

                return config;
            }
            catch (Exception ex)
            {
                Mediator.Instance.NotifyColleaguesAsync<string>(MessageType.EXCEPTION_FOUND, ex.Message);

                return default(T);
            }
            finally
            {
                if (tw != null)
                {
                    tw.Close();
                    tw.Dispose();
                }
            }
        }

        public static bool Serializa(object config, string filename)
        {
            try
            {
                using (TextWriter tw = new StreamWriter(filename))
                {
                    System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(config.GetType());
                    x.Serialize(tw, config);

                    tw.Flush();

                    return true;
                }
            }
            catch
            {
                return false;
            }
        }
    }
}
